package com.peking.donations.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 利用XStream执行Object、Json和XML之间的转换
 *
 * @author hawk
 *
 */
public class XMLUtil {
	private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);

	@SuppressWarnings("unchecked")
	public static Map<String, String> fromXml(String xml) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			Element root = document.getRootElement();
			List<Element> elementList = root.elements();
			for (Element e : elementList)
				//遍历xml将数据写入map
				map.put(e.getName(), e.getText());
			inputStream.close();
			inputStream = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static String toXML(Map<String, String> m) {
		XStream xstream = new XStream(new XppDriver() {
	        public HierarchicalStreamWriter createWriter(Writer out) {
	            return new PrettyPrintWriter(out) {
	                // 对所有xml节点的转换都增加CDATA标记
	                boolean cdata = true;  
	                @SuppressWarnings("rawtypes")
					public void startNode(String name, Class clazz) {  
	                    super.startNode(name, clazz);  
	                }  
	                protected void writeText(QuickWriter writer, String text) {  
	                    if (cdata) {  
	                        writer.write("<![CDATA[");  
	                        writer.write(text);  
	                        writer.write("]]>");  
	                    } else {  
	                        writer.write(text);  
	                    }  
	                }  
	            };  
	        }  
	    }); 
		String s = xstream.toXML(m);
		logger.debug(s);
		return s;
	}
	
	public static void main(String[] args) {
		String s="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg><mch_appid><![CDATA[wx2ea510113b49e9b9]]></mch_appid><mchid><![CDATA[1226972102]]></mchid><device_info><![CDATA[]]></device_info><nonce_str><![CDATA[74371899]]></nonce_str><result_code><![CDATA[SUCCESS]]></result_code><partner_trade_no><![CDATA[N100001]]></partner_trade_no><payment_no><![CDATA[1000018301201504280115627375]]></payment_no><payment_time><![CDATA[2015-04-28 15:26:53]]></payment_time></xml>";
		Map<String, String> m = XMLUtil.fromXml(s);
		System.out.println(m);
		
		s = XMLUtil.toXML(m);
		System.out.println(s);
//		Map<String, Object> m = Maps.newHashMap();
//		m.put("appId", "wx123435");
//		m.put("joined", new Date());
//	
//		System.out.println(XStreamUtil.toXML(m));
//		String json = XStreamUtil.toJson(m);
//		Map<String, Object> m2 = XStreamUtil.fromJson(json);
//		
//		String xml = XStreamUtil.toXML(m2);
//		Map<String, Object> m3 = XStreamUtil.fromXml(xml);
//		
//		System.out.println(m);
//		System.out.println(m2);
//		System.out.println(m3);
		
	}
}
